package cn.royan.fl.services 
{
	import cn.royan.fl.events.NetworkEvent;
	import cn.royan.fl.interfaces.INetworkProtocol;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.net.URLVariables;
	
	/**
	 * ...
	 * @author RoYan
	 */
	public class SingleULRLoaderProtocol extends EventDispatcher implements INetworkProtocol 
	{
		private var loader:URLLoader;
		private var request:URLRequest;
		private var variable:URLVariables;
		private var isLoading:Boolean;
		
		public function SingleULRLoaderProtocol( variable:String ) 
		{
			super();
			
			if ( variable ) this.variable = new URLVariables( variable );
		}
		
		public function sendRequest( request:* = null, extra:* = null ):void
		{
			this.request = new URLRequest( request );
			this.request.method = extra?extra:URLRequestMethod.GET;
			if ( variable ) this.request.data = variable;
		}
		
		public function connect():void
		{
			if ( isLoading ) disconnect();
			
			loader = new URLLoader();
			loader.dataFormat = URLLoaderDataFormat.BINARY;
			loader.addEventListener( Event.COMPLETE, completeHandler );
			loader.addEventListener( ProgressEvent.PROGRESS, progressHandler );
			
			loader.addEventListener( IOErrorEvent.IO_ERROR, errorHandler );
			loader.addEventListener( IOErrorEvent.DISK_ERROR, errorHandler );
			loader.addEventListener( IOErrorEvent.VERIFY_ERROR, errorHandler );
			loader.addEventListener( IOErrorEvent.NETWORK_ERROR, errorHandler );
			loader.load( request );
			isLoading = true;
		}
		
		public function disconnect():void
		{
			
		}
		
		public function getData():*
		{
			
		}
		
		private function completeHandler(evt:Event):Void
		{
			Logger.log( "LOAD COMPLETE: " + request.url );
			isLoading = false;
			data = loader.data;
			
			dispatchEvent( new NetworkEvent( NetworkEvent.NETWORK_RESULT, data ) );
			
			disconnect();
		}
		
		private function errorHandler(evt:IOErrorEvent):Void
		{
			Logger.log( "LOAD ERROR: " + request.url + " TYPE: " + evt.type );
			isLoading = false;
			
			dispatchEvent( new NetworkEvent( NetworkEvent.NETWORK_ERROR, evt.type ) );
			
			disconnect();
		}
		
		private function progressHandler(evt:ProgressEvent):Void
		{
			Logger.log( "LOAD PROGRESS: " + request.url );
			
			dispatchEvent( new NetworkEvent( NetworkEvent.NETWORK_PROGRESS, evt.bytesLoaded / evt.bytesTotal ) );
		}
	}

}